package de.justphil.tcg.tcgserver.rest.resources.helpers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.activation.MimetypesFileTypeMap;
import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;

import de.justphil.tcg.tcgserver.commons.exceptions.TCGException;
import de.justphil.tcg.tcgserver.commons.i18n.Error;
import de.justphil.tcg.tcgserver.commons.util.StringUtil;

public class IndexHelper {
	
	private static final String FILE_ENDING_SEPARATOR = Pattern.quote( "." );
	
	private static final MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
	
	private static final Map<String, String> knownMimeTypesMap = new HashMap<String, String>();
	
	static {
		knownMimeTypesMap.put("js", "application/javascript");
		knownMimeTypesMap.put("css", "text/css");
		knownMimeTypesMap.put("png", "image/png");
	}
	
	
	
	public static String getHtmlFile(String filename) throws TCGException {
		
		StringBuilder sb = new StringBuilder(64);
		sb.append("htdocs").append(File.separator).append(filename);
		
		return getFileContentContainer( sb.toString() ).getFileContent();
		
	}
	
	public static FileContentContainer getAssetFile(String filename) throws TCGException {
		
		StringBuilder sb = new StringBuilder(128);
		sb.append("htdocs").append(File.separator).append("assets").append(File.separator).append(filename);
		
		return getFileContentContainer( sb.toString() );
		
	}
	
	private static FileContentContainer getFileContentContainer(String filePath) throws TCGException {
		
		try {
			if (StringUtil.isNullOrEmpty(filePath) || filePath.contains( ".." )) {
				throw new TCGException(Error.CLIENT_ERROR_INVALID_REQUEST_URI, Response.Status.BAD_REQUEST);
			}
			
			
			FileReader fr = new FileReader(filePath);
			return new FileContentContainer( getMimeTypeByFileEnding(filePath), IOUtils.toString(fr) );
		}
		catch (FileNotFoundException e) {
			throw new TCGException(Error.CLIENT_ERROR_FILE_NOT_FOUND, Response.Status.NOT_FOUND);
		}
		catch (IOException e) {
			throw new TCGException(Error.SERVER_ERROR_INTERNAL, Response.Status.INTERNAL_SERVER_ERROR);
		}
		
	}
	
	private static String getMimeTypeByFileEnding( String filePath ) {
		String out = "text/plain";
		
		String[] segs = filePath.split( FILE_ENDING_SEPARATOR );
		
		if (segs.length == 0) {
			return out;
		}
		
		out = knownMimeTypesMap.get( segs[segs.length-1] );
		if (out == null) {
			out = mimeTypesMap.getContentType(filePath);
		}
		
		return out;
	}

}
